package com.kg.tombs.controller;

import com.kg.tombs.db.MongoVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;

public class DataController {

    private final Vertx vertx;

    private final MongoVerticle mongoVerticle;

    public DataController(Vertx vertx, MongoVerticle mongoVerticle) {
        this.vertx = vertx;
        this.mongoVerticle = mongoVerticle;
    }

    public void getCollections(RoutingContext ctx){
        mongoVerticle.listCollections()
                .onSuccess(result -> ctx.response()
                        .putHeader("Content-Type", "application/json")
                        .end(result.encode()))
                .onFailure(err -> sendError(ctx, 500, err.getMessage()));
    }

    public void getAll(RoutingContext ctx) {
        String collection =  ctx.request().getParam("collection");
        mongoVerticle.find(collection,new JsonObject())
                .onSuccess(result -> ctx.response()
                        .putHeader("Content-Type", "application/json")
                        .end(result.toString()))
                .onFailure(err -> sendError(ctx, 500, err.getMessage()));
    }


    private void sendError(RoutingContext ctx, int code, String message) {
        ctx.response()
                .setStatusCode(code)
                .end(new JsonObject().put("error", message).encode());
    }
}
